#include "photonEngine.h"

using namespace PhotonEngine;

Engine::Engine() {

}

Engine::~Engine() {

}

bool Engine::reshape(int x, int y, int width, int height) {
	if (x < 0) {
		x = 0;
	}
	if (y < 0) {
		y = 0;
	}
	if (width < 0) {
		width = 0;
	}
	if (height < 0) {
		height = 0;
	}
	
#ifdef _WINDOWS
	MoveWindow(this->engineWindow, x, y, width, height, TRUE);
#endif
	this->renderManager.reshapeWindow(x, y, width, height);

	return true;
}

bool Engine::createWindow(WNDPROC WndProc, HINSTANCE hInstance, const char* title, int x, int y, int width, int height, HWND parentWindow) {
	WNDCLASSEX openglClass;

	openglClass.cbSize = sizeof(WNDCLASSEX);
    openglClass.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    openglClass.lpfnWndProc    = WndProc;
    openglClass.cbClsExtra     = 0;
    openglClass.cbWndExtra     = 0;
    openglClass.hInstance      = hInstance;
    openglClass.hIcon          = NULL;
    openglClass.hCursor        = LoadCursor(NULL, IDC_ARROW);
    openglClass.hbrBackground  = NULL;
    openglClass.lpszMenuName   = NULL;
    openglClass.lpszClassName  = title;
    openglClass.hIconSm        = NULL;

	if (!RegisterClassEx(&openglClass)) {
		MessageBox(NULL, NULL, NULL, NULL);
		return false;
	}

	this->engineWindow = CreateWindowA(title, title, WS_CHILD | WS_VISIBLE, x, y, width, height, parentWindow, NULL, hInstance, NULL);
	this->programHInstance = hInstance;
	this->parentWindow = parentWindow;

	return true;
}

bool Engine::start() {
#ifdef _WINDOWS
	// enable super accurate Sleeping
	timeBeginPeriod(1);

	// Setup the RenderManager
	renderManager.setup(engineWindow, this->renderOptions);
#endif
	
	// Initialize some global stuff
	
	// Start up all the sub-systems
	renderManager.start(1);

	// Test

	return true;
}

void Engine::renderFrame() {
	renderManager.renderOptions = renderOptions;
	renderManager.renderFrame = true;
}

void Engine::shutDown() {
	// disable super accurate Sleeping
#ifdef _WINDOWS
	timeEndPeriod(1);
#endif

	// Shutdown Threads (reverse of startup)
	renderManager.join();
}

const char* convertBoolToString(bool variable) {
	if (variable) {
		return "TRUE";
	} else {
		return "FALSE";
	}
}

void Engine::printOptions() {
	// Open file
	std::ofstream optionsFile;
	optionsFile.open(ENGINEOPTIONSFILE);
	if (optionsFile.is_open()) {
		optionsFile << "PhotonEngine Options\n";
		//optionsFile << "variable = value;\n";
		
	} else {
		
	}
	optionsFile.close();
}

bool stringToBool(const char* string) {
	if (string == "TRUE") {
		return true;
	} else {
		return false;
	}
}

void Engine::loadOptions() {
	std::ifstream optionsFile;
	optionsFile.open(ENGINEOPTIONSFILE);
	std::string line;

	if (optionsFile.is_open()) {
		while (optionsFile.good()) {
			std::getline(optionsFile, line);
			
		}
	}
}